package com.indusfo.spc.controller;

import com.indusfo.spc.aspect.SystemControllerLog;
import com.indusfo.spc.pojo.Batch;
import com.indusfo.spc.pojo.Dosing;
import com.indusfo.spc.pojo.ExcelErrorData;
import com.indusfo.spc.pojo.Order;
import com.indusfo.spc.service.BatchFlowService;
import com.indusfo.spc.service.BatchService;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务单分解批次控制层
 */
@Controller
@RequestMapping("/service/batch")
public class BatchController {

    @Autowired
    private BatchService batchService;


    /**
     * 新增任务单分解批次
     *
     * @param batch
     * @return
     */
    @RequestMapping(value = "/insertBatch")
    @SystemControllerLog(description = "新增任务单分解批次")
    @ResponseBody
    public JSONObject insertBatch(Batch batch, Integer num , Integer planNum) {

        JSONObject json = batchService.insertBatch(batch, num, planNum);

        return json;
    }

    /**
     * 查询
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/queryBatch")
    @SystemControllerLog(description = "查询")
    @ResponseBody
    public JSONObject queryBatch(Batch batch) {

        JSONObject json = batchService.selectBatch(batch);
        return json;

    }

    /**
     * 查询所有批次
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/queryBatchAll")
    @SystemControllerLog(description = "查询所有")
    @ResponseBody
    public JSONObject queryBatchAll(Batch batch) {

        JSONObject json = batchService.queryBatchAll(batch);
        return json;

    }

    /**
     * 查询任务单
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/queryOrder")
    @SystemControllerLog(description = "查询")
    @ResponseBody
    public JSONObject queryOrder(Order order) {

        JSONObject json = batchService.queryOrder(order);
        return json;

    }

    /**
     * 查询批次任务单
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value="/queryBatchOrder")
    @SystemControllerLog(description="查询")
    @ResponseBody
    public JSONObject queryBatchOrder(Batch batch) {

        JSONObject json = batchService.queryBatchOrder(batch);
        return json;

    }


    /**
     * 删除
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/delBatch")
    @SystemControllerLog(description = "删除")
    @ResponseBody
    public JSONObject delBatch(Long[] BatchIds , Long[] productStateIds) {

        JSONObject json = batchService.delBatch(BatchIds , productStateIds);
        return json;

    }

    /**
     * 打印
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/printBatch")
    @SystemControllerLog(description = "打印")
    @ResponseBody
    public JSONObject printBatch(Long[] BatchIds) {

        JSONObject json = batchService.printBatch(BatchIds);
        return json;

    }

    /**
     * 打印根据批号
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/printBatchCode")
    @SystemControllerLog(description = "打印根据批号")
    @ResponseBody
    public JSONObject printBatchCode(String[] batchCodes) {
        JSONObject json = batchService.printBatchCode(batchCodes);
        return json;
    }

    /**
     * 查询个数
     *
     * @param
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/numBatch")
    @SystemControllerLog(description = "查询个数")
    @ResponseBody
    public JSONObject numBatch(Batch batch) {

        JSONObject json = batchService.numBatch(batch);
        return json;

    }

    /**
     * 保存工序流程
     */
    @RequestMapping(value = "/saveBatchFlow", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveBatchFlow(@RequestBody Batch batch) {
        JSONObject json = batchService.saveBatchFlow(batch);
        return json;
    }

    /**
     * 保存维修流程
     */
    @RequestMapping(value = "/saveBatchRepair", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveBatchRepair(@RequestBody Batch batch) {
        JSONObject json = batchService.saveBatchRepair(batch);
        return json;
    }

    /**
     * 复制批次流程
     */

    @RequestMapping(value = "/uploadFileBatch")
    @ResponseBody
    public JSONObject uploadFileBatch(@RequestParam("file") MultipartFile file, Boolean way,Batch batch, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String checkParamResult=batchService.checkParam(batch);

        Integer orderFlowId = batchService.queryNowFlowId(batch.getOrderTechId());


        if(!StringUtils.isEmpty(checkParamResult)){
            return JSONObject.build(JSONObject.ERROR,checkParamResult);
        }
        //定义一个message对象用于向前台传输数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            jsonObject.setStatus(JSONObject.ERROR);
            jsonObject.setMsg("文件解析错误");
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {

                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    jsonObject.setMsg("未找到需要导入的数据，请确认物料信息表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认料信息表格是否保存！！！"));
                } else {
                    List<Batch> batchList = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //批次编码
                        String batchCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        Batch newBatch=new Batch();
                        newBatch.setOrderId(batch.getOrderId());
                        newBatch.setOrderFlowId(orderFlowId);
                        newBatch.setOrderFlowStateId(1);
                        newBatch.setUserId(batch.getUserId());
                        newBatch.setBatchCode(batchCode);
                        //将excel中的每一行数据存储进行检查
                        String result = batchService.checkExcelContent(newBatch);
                        if (result != null) {
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd = false;
                        }
                        for (int j = 1; j < i; j++) {
                            //判断物料编码  物料名称是否重复
                            String oldBatchCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false);
                            if (!StringUtils.isBlank(batchCode) && oldBatchCode.equals(batchCode)) {
                                needAdd = false;
                                errorDatas.add(ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同批次编码"));
                            }
                        }
                        if (needAdd) {
                            batchList.add(newBatch);
                        } else {
                            jsonObject.setStatus(JSONObject.ERROR);
                            jsonObject.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR) && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (batchList.size() > 0) {
                            try {
                                batchService.updateListBatch(batchList);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }
                }
            }
        }
        jsonObject.setData(GsonUtil.toJson(errorDatas));
        //response.getWriter().println(GsonUtil.toJson(msg));
        return JSONObject.build(JSONObject.SUCCESS, jsonObject.getMsg(), errorDatas);
    }

}
